package com.zhihuishu.micro.course.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;

import com.alibaba.fastjson.JSONArray;
import com.zhihuishu.micro.course.dao.WonderVideoMapper;
import com.zhihuishu.micro.course.helper.RedisKeyHelper;
import com.zhihuishu.micro.course.model.WonderVideo;
import com.zhihuishu.micro.course.service.WonderVideoService;
import com.zhihuishu.toolkit.helper.BeanHelper;
import com.zhihuishu.toolkit.jedis.BeanWrapper;
import com.zhihuishu.toolkit.jedis.JedisHelper;
import com.zhihuishu.toolkit.jedis.JedisHelper.Handler;
import com.zhihuishu.toolkit.jedis.JedisHelper.ReturnHandler;

/** 
 * @author yulijin 
 * @version 创建时间：2016年12月14日 下午3:01:40 
 * 类说明 
 */
@Service("wonderVideoService")
public class WonderVideoServiceImpl extends BaseService implements WonderVideoService {
	@Resource
	private WonderVideoMapper wonderVideoMapper ;
	
	@Override
	public WonderVideo save(WonderVideo wonderVideo) {
		wonderVideoMapper.save(wonderVideo);
		//保存到redis
		saveOrUpdateToRedis(wonderVideo);
	    //删除同一个courseId下面的精彩视频ids
		delRedisWonderVideoIds(wonderVideo.getCourseId());
		return wonderVideo;
	}

	@Override
	public void update(WonderVideo wonderVideo) {
		wonderVideoMapper.update(wonderVideo);
		//修改时维护缓存，需要查全数据
		wonderVideo = wonderVideoMapper.findWonderVideo(wonderVideo.getWonderVideoId());
		//修改到redis
		saveOrUpdateToRedis(wonderVideo);
	}

	@Override
	public void remove(final Long wonderVideoId) {
//		Jedis jedis= null;
//        try {
//        	jedis=jedisPool.getResource();
//        	wonderVideoMapper.remove(wonderVideoId);
//    		//从缓存中获取courseId,删除精彩视频ids
//        	WonderVideo wonderVideo = getWonderVideo(wonderVideoId,jedis);
//        	if(wonderVideo != null){
//        		delRedisWonderVideoIds(wonderVideo.getCourseId());
//        	}
//    		//从redis中删除精彩视频数据
//    		delRedisWonderVideo(wonderVideoId);	
//		}finally{
//			JedisHelper.closeQuietly(jedis);
//		}
        jedisExecutor.execute(new Handler() {
        	@Override
        	public void handle(Jedis jedis) {
            	wonderVideoMapper.remove(wonderVideoId);
        		//从缓存中获取courseId,删除精彩视频ids
            	WonderVideo wonderVideo = getWonderVideo(wonderVideoId,jedis);
            	if(wonderVideo != null){
            		delRedisWonderVideoIds(wonderVideo.getCourseId());
            	}
        		//从redis中删除精彩视频数据
        		delRedisWonderVideo(wonderVideoId);	
         	}
        });
	}
	@Override
	public WonderVideo findWonderVideo(final Long wonderVideoId) {
//		WonderVideo wonderVideo = null;
//		Jedis jedis= null;
//        try {
//        	jedis=jedisPool.getResource();
//        	wonderVideo = getWonderVideo(wonderVideoId,jedis);
//		}finally{
//			JedisHelper.closeQuietly(jedis);
//		}
//		return wonderVideo;
		BeanWrapper<WonderVideo> bw = jedisExecutor.executeAndReturn(new ReturnHandler<WonderVideo>() {
			@Override
			public WonderVideo handle(Jedis jedis) {
				
				return getWonderVideo(wonderVideoId,jedis);
			}
		});
		return bw.getValue();
	}
	@Override
	public List<WonderVideo> findWonderVideosByCourseId(final Long courseId) {
		//从redis中获取数据
//		List<WonderVideo> wonderVideos = null;
//			Jedis jedis= null;
//	        try {
//	        	jedis = jedisPool.getResource();
//	        	wonderVideos = findWonderVideoList(courseId,jedis);
//			}finally{
//				JedisHelper.closeQuietly(jedis);
//			}
//		return wonderVideos;
		BeanWrapper<List<WonderVideo>> bw = jedisExecutor.executeAndReturn(new ReturnHandler<List<WonderVideo>>() {
			@Override
			public List<WonderVideo> handle(Jedis jedis) {
				
				return findWonderVideoList(courseId,jedis);
			}
		});
		return bw.getValue();
		
	}
    /**
     * 保存或修改到redis
     * @author yulijin
     * @date 2016年12月15日 上午10:46:14 
     * @param wonderVideo
     * @return
     */
    private WonderVideo saveOrUpdateToRedis(final WonderVideo wonderVideo){
    	if(wonderVideo == null){
    		return null;
    	}
    	final Map<String,String> map = BeanHelper.describe(wonderVideo);
        
		jedisExecutor.execute( new Handler() {
			@Override
			public void handle(Jedis jedis) {
				jedis.hmset(RedisKeyHelper.getWonderVideoKey(wonderVideo.getWonderVideoId()),map);
			}
		});
    	return wonderVideo;
    }
    /**
     * 删除精彩视频redis
     * @author yulijin
     * @date 2016年12月15日 上午10:49:46 
     * @param wonderVideoId
     */
    private void delRedisWonderVideo(final Long wonderVideoId){
		jedisExecutor.execute( new Handler() {
			String wonderVideoKey = RedisKeyHelper.getWonderVideoKey(wonderVideoId);
			@Override
			public void handle(Jedis jedis) {
				jedis.del(wonderVideoKey);
			}
		});
    }
    /**
     * 获取精彩视频
     * @author yulijin
     * @date 2016年12月15日 上午11:25:03 
     * @param wonderVideo
     * @return
     */
    private WonderVideo getWonderVideo(Long wonderVideoId,Jedis jedis){
    	WonderVideo wonderVideo = null;
    	String key = RedisKeyHelper.getWonderVideoKey(wonderVideoId);
    	if(jedis.exists(key)){
    		//从redis中获取
        	Map<String,String> map = jedis.hgetAll(key);
			if(map != null && map.size()>0){
				wonderVideo = BeanHelper.transTo(map, WonderVideo.class);
			}
    	}
    	//如果redis中没有数据，则从数据库中获取，并将数据存入redis
		if(wonderVideo == null){
			wonderVideo = wonderVideoMapper.findWonderVideo(wonderVideoId);
			Map<String,String> wonderVideoMap = BeanHelper.describe(wonderVideo);
			jedis.hmset(RedisKeyHelper.getWonderVideoKey(wonderVideoId),wonderVideoMap);
		}
    	return wonderVideo;
    }

    private void delRedisWonderVideoIds(final Long courseId){
        /*String key = RedisKeyHelper.getWonderVideoIdsKey(courseId);
    	Jedis jedis= null;
        try {
        	jedis = jedisPool.getResource();
        	jedis.del(key);
		}finally{
			JedisHelper.closeQuietly(jedis);
		}*/
    	jedisExecutor.execute(new Handler() {
            
            @Override
            public void handle(Jedis jedis) {
                
                jedis.del(RedisKeyHelper.getWonderVideoIdsKey(courseId));
                
            }
        });
    }
    /**
     * 从redis中获取精彩视频ids
     * @author yulijin
     * @date 2016年12月15日 下午2:27:36 
     * @param wonderVideos
     * @param courseId
     */
    private List<WonderVideo> findWonderVideoList(Long courseId,Jedis jedis){
    	List<WonderVideo> wonderVideos = null;
    	WonderVideo wonderVideo = null;
    	//从redis中获取
    	String wonderVideoIdsKey = RedisKeyHelper.getWonderVideoIdsKey(courseId);
    	String strIds = jedis.get(wonderVideoIdsKey);
    	if(StringUtils.isNotEmpty(strIds)){
    		wonderVideos = new ArrayList<WonderVideo>();
    		List<Long> ids = JSONArray.parseArray(strIds, Long.class);
    		for(Long id : ids){
    			wonderVideo = getWonderVideo(id , jedis);
    			if(wonderVideo != null){
    				wonderVideos.add(wonderVideo);
    			}
    		}
    	}
    	//如果redis中没有数据，则从数据库中获取
    	if(CollectionUtils.isEmpty(wonderVideos)){
    		wonderVideos = wonderVideoMapper.findWonderVideosByCourseId(courseId);
    		if(CollectionUtils.isNotEmpty(wonderVideos)){
    			List<Long> ids = new ArrayList<Long>() ;
    			for(WonderVideo wv : wonderVideos){
    				ids.add(wv.getWonderVideoId());
    			}
    			jedis.set(wonderVideoIdsKey, JSONArray.toJSON(ids).toString());
    		}
    	}
    	
    	return wonderVideos;
    }
    

}
